package com.hntxk.cqzd.basicinfo.basepatient.service.impl;


import com.hntxk.core.ext.mybatis.adapter.SQLAdapter;

import com.hntxk.core.framework.service.impl.BaseServiceImpl;
import com.hntxk.core.util.StringUtil;
import com.hntxk.cqzd.basicinfo.basepatient.entity.BasePatient;
import com.hntxk.cqzd.basicinfo.basepatient.service.BasePatientManageService;
import com.hntxk.cqzd.diacrisis.entity.TblDiacrisisInfo;
import com.hntxk.sp.dict.manager.DictManager;
import com.hntxk.sp.dict.model.Dict;
import com.hntxk.sp.log.model.ActionLog;
import com.hntxk.sp.log.model.ActionType;
import com.hntxk.sp.util.LogRecordUtil;
import com.hntxk.sp.util.LoginUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.*;

/**
 * @author <a href="huangbiquan@hotmail.com">Huang.Biquan</a>
 * @Description: 基本信息管理接口实现类 <br>
 * @Project: SP <br>
 * @date 2019/6/3 10:01 <br>
 */
@Service("basePatientService")
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class BasePatientManageServiceImpl extends BaseServiceImpl<BasePatient> implements BasePatientManageService {



    public static String BASE_PATIENT_MAPPER_NAMESPACE = "com.hntxk.cqzd.basicinfo.basepatient.mapper.BasePatientMapper.";

    public BasePatientManageServiceImpl() {

        super(BASE_PATIENT_MAPPER_NAMESPACE);
    }

    //增加修改需要设置值的方法
    public TblDiacrisisInfo commenSet(TblDiacrisisInfo basePatient) throws ParseException {
        basePatient.setPatientSex('f');

        if(StringUtil.isNotNull(basePatient.getPatientCardId())){
            //校验身份证
            String regIdCard = "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)";
            boolean b = basePatient.getPatientCardId().matches(regIdCard);
            if(b==false){
                throw new IllegalArgumentException("身份证输入有误");
            }
        }else{
            throw new RuntimeException("请输入身份证号");
        }

        String patientTel = basePatient.getPatientTel();
        if(patientTel==null || patientTel=="" ||"".equals(patientTel)) {

        }else{
            //校验电话号码
            String tel = "(^(0\\d{2,3}-\\d{7,8}))|(^1[3456789]\\d{9}$)";
            boolean matches = patientTel.matches(tel);
            if (!matches) {
                throw new IllegalArgumentException("电话号码输入有误");
            }
        }

        String spouseTel = basePatient.getSpouseTel();
        if(spouseTel==null || spouseTel=="" ||"".equals(spouseTel)) {

        }else{
            //校验电话号码
            String tel = "(^(0\\d{2,3}-\\d{7,8}))|(^1[3456789]\\d{9}$)";
            boolean matches = spouseTel.matches(tel);
            if (!matches) {
                throw new IllegalArgumentException("电话号码输入有误");
            }
        }

        if(basePatient.getPatientBirthday()!=null) {
            //设置年龄
            int age = getAgeByBirth(basePatient.getPatientBirthday());
            basePatient.setPatientAge(age);
        }

        Long patientRaceId = basePatient.getPatientRaceId();
        //设置民族id值
        if(patientRaceId==null){
            basePatient.setPatientRaceId((long) 1);
        }
        Long patientEduId = basePatient.getPatientEduId(); //患者学历id
        Long spouseEduId = basePatient.getSpouseEduId(); //配偶学历id
        Long patientOccupationId = basePatient.getPatientOccupationId();  //患者职业id
        Long spouseOccupationId = basePatient.getSpouseOccupationId(); //配偶职业id
        if(patientEduId!=null){
            //设置患者学历下拉name
            Dict baseEdu = DictManager.getInstance().getDict("CQ_BASE_EDU", patientEduId);
            basePatient.setPatientEdu(baseEdu.getText());
        }
        if(spouseEduId!=null){
            //设置患者配偶学历下拉name
            Dict spouseEdu = DictManager.getInstance().getDict("CQ_BASE_EDU", spouseEduId);
            basePatient.setSpouseEdu(spouseEdu.getText());
        }

        if(patientOccupationId!=null){
            //设置患者职业下拉name
            Dict baseOccupation = DictManager.getInstance().getDict("CQ_BASE_OCCUPATION", patientOccupationId);
            basePatient.setPatientOccupation(baseOccupation.getText());
        }

        if(spouseOccupationId!=null){
            //设置配偶职业下拉name
            Dict spouseOccupationIdDict = DictManager.getInstance().getDict("CQ_BASE_OCCUPATION", spouseOccupationId);
            basePatient.setSpouseOccupation(spouseOccupationIdDict.getText());
        }

        Long patientReligionId = basePatient.getPatientReligionId(); //宗教信仰
        if (patientReligionId!=null) {
            //设置宗教信仰下拉name
            Dict baseReligion = DictManager.getInstance().getDict("CQ_BASE_RELIGION", patientReligionId);
            basePatient.setPatientReligion(baseReligion.getText());
        }

        return basePatient;
    }

    //新增患者信息
    @Override
    public TblDiacrisisInfo insert(TblDiacrisisInfo basePatient) throws ParseException {
        if (basePatient.getPatientId()==null) {
            BasePatient patient=new BasePatient();
            basePatient.setPatientId((Long) getPrimaryKey(patient));
        }

        basePatient = commenSet(basePatient);
        //根据身份证号判断是否已经存在改患者信息
        int count = super.count(BASE_PATIENT_MAPPER_NAMESPACE + "countBasePatient", basePatient);
        if (count==0){
            basePatient.setCreateTime(new Date());
            basePatient.setCreateUserId(LoginUserUtil.getLoginOperatorIdLong());

            basePatient.setCreateUserName(LoginUserUtil.getLoginUserName());
            insert(BASE_PATIENT_MAPPER_NAMESPACE+"insert",basePatient);
            //记录日志
            Long aLong = LogRecordUtil.addLog(new ActionLog(BasePatient.class, basePatient.getPatientId() + "", "12",
                    ActionType.ADD, "新增了患者基本信息：" + basePatient.getPatientId() + "[ " + basePatient.getPatientName() + " ]"));
//            System.out.println(aLong);
            return basePatient;
        }else{
            //已经存在改用户  以下信息不能修改
          TblDiacrisisInfo  getOne=get(BASE_PATIENT_MAPPER_NAMESPACE+"getByCard",basePatient);
            basePatient.setPatientId( getOne.getPatientId());
            basePatient.setPatientName(getOne.getPatientName());
            basePatient.setCreateTime(getOne.getCreateTime());
            basePatient.setCreateUserId(getOne.getCreateUserId());
            basePatient.setCreateUserName(getOne.getCreateUserName());
            basePatient.setPatientBirthday(getOne.getPatientBirthday());
            TblDiacrisisInfo update = update(basePatient);
            return update;
//            throw new RuntimeException("已经存在该患者信息！");
        }
    }


    //手机端新增患者信息
    @Override
    public TblDiacrisisInfo insertPhone(TblDiacrisisInfo basePatient) throws ParseException {
        if (basePatient.getPatientId()==null) {
            BasePatient patient=new BasePatient();
            basePatient.setPatientId((Long) getPrimaryKey(patient));
        }

        basePatient = commenSet(basePatient);
//        int count=0;
//        //根据身份证号判断是否已经存在改患者信息
//        if(StringUtil.isNotNull(basePatient.getPatientCardId())){
//            String sql = "select count(0) from tbl_base_patient t where t.patient_card_id='"+basePatient.getPatientCardId()+"'";
//            count = getDasTemplate().selectOne("SQLMapper.count", new SQLAdapter(sql));
//        }
        int count = super.count(BASE_PATIENT_MAPPER_NAMESPACE + "countBasePatient", basePatient);
        if (count==0){
            basePatient.setCreateTime(new Date());
            basePatient.setCreateUserId((long) -1024);

            basePatient.setCreateUserName("手机用户");
            insert(BASE_PATIENT_MAPPER_NAMESPACE+"insert",basePatient);
            return basePatient;
        }else{
            //已经存在改用户  以下信息不能修改
            TblDiacrisisInfo  getOne=get(BASE_PATIENT_MAPPER_NAMESPACE+"getByCard",basePatient);
            basePatient.setPatientId( getOne.getPatientId());
            basePatient.setPatientName(getOne.getPatientName());
            basePatient.setCreateTime(getOne.getCreateTime());
            basePatient.setCreateUserId(getOne.getCreateUserId());
            basePatient.setCreateUserName(getOne.getCreateUserName());
            basePatient.setPatientBirthday(getOne.getPatientBirthday());
            TblDiacrisisInfo update = update(basePatient);
            return update;
        }
    }



    //删除患者信息
    @Override
    public void delete(String ids, boolean isCalled) {
       List<String> list = Arrays.asList(ids.split(","));
        List<BasePatient> basePatients=new ArrayList<>();
        for (String id : list) {
            basePatients.add(get(Long.parseLong(id)));
            delete(BASE_PATIENT_MAPPER_NAMESPACE+"delete",id);
        }
        for(BasePatient basePatient:basePatients)
            LogRecordUtil.addLog(new ActionLog(BasePatient.class, basePatient.getPatientId() + "", "12",
                    ActionType.DELETE, "删除患者基本信息：" + basePatient.getPatientCode() + "[ " + basePatient.getPatientName() + " ]"));

    }

    //修改患者信息
    @Override
    public TblDiacrisisInfo update(TblDiacrisisInfo basePatient) throws ParseException {
        if (basePatient.getPatientId()==null) {
            BasePatient patient=new BasePatient();
            basePatient.setPatientId((Long) getPrimaryKey(patient));
        }
        basePatient = commenSet(basePatient);
        basePatient.setUpdateTime(new Date());
        basePatient.setUpdateUserId(LoginUserUtil.getLoginOperatorIdLong());
        basePatient.setUpdateUserName(LoginUserUtil.getLoginUserName());
        super.update(BASE_PATIENT_MAPPER_NAMESPACE + "update", basePatient);
        if (LoginUserUtil.isLogin()) {
            //记录日志
            LogRecordUtil.addLog(new ActionLog(BasePatient.class, basePatient.getPatientId() + "", "12",
                    ActionType.UPDATE, "修改了患者基本信息：" + basePatient.getPatientCode() + "[ " + basePatient.getPatientName() + " ]"));
        }
         return basePatient;
    }
    //根据日期计算年龄
    public static int getAgeByBirth(Date birthDay){
        int age = 0;
        Calendar cal = Calendar.getInstance();
        Calendar calBirDay = Calendar.getInstance();
        calBirDay.setTime(birthDay);
        if (cal.before(calBirDay)) { //出生日期晚于当前时间，无法计算
            throw new IllegalArgumentException(
                    "出生日期晚于当前时间，无法计算!");
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
            } else {
                age--;//当前月份在生日之前，年龄减一
            }
        }
        return age;
    }


}
